/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.ulss.monitor.mainserver;

import static cn.ac.iie.commons.config.RunTimeEnv.NAME_NODE_MAP;
import static cn.ac.iie.commons.config.RunTimeEnv.dynamicParams;
import static cn.ac.iie.ulss.monitor.mainserver.ComplexHandler.logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.I0Itec.zkclient.ZkClient;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

/**
 *
 * @author YY
 */
public class ComplexHandler extends AbstractHandler {

    private static ComplexHandler infoPubHandler = null;
    static Logger logger = Logger.getLogger(ServerStartup.class.getName());

    private ComplexHandler() {
    }

    public static ComplexHandler getInfoPubHandler() {
        if (infoPubHandler == null) {
            infoPubHandler = new ComplexHandler();
        }
        return infoPubHandler;
    }

    /**
     *
     * @param string
     * @param baseRequest
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(String string, Request baseRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        baseRequest.setHandled(true);
        String remoteHost = baseRequest.getRemoteAddr();
        int remotePort = baseRequest.getRemotePort();
        String reqID = String.valueOf(System.nanoTime());
        logger.info("receive request from " + remoteHost + ":" + remotePort + " and assigned id " + reqID);
        String ddStatus = null;
        String path = "/home/ulss/monitor/ddStatus.sh";
        Process p = null;
        p = Runtime.getRuntime().exec(path);
        try {
            p.waitFor();
        } catch (InterruptedException ex) {
            logger.error(ex);
        }
        List<Object> list = new ArrayList<Object>();
        Map<String, String> nodes = new HashMap<String, String>();
        Map<String, String> name2Node = (Map<String, String>) dynamicParams.get(NAME_NODE_MAP);
//        Map<Integer, String> count2Node = new HashMap<Integer, String>();
//        name2Node.put("load4:", "11.1.32.68");
//        name2Node.put("load5:", "11.1.32.69");
//        name2Node.put("load6:", "11.1.32.70");
//        name2Node.put("load7:", "11.1.32.171");
//        name2Node.put("load8:", "11.1.32.172");
//        name2Node.put("load9:", "11.1.32.173");
//        name2Node.put("load10:", "11.1.32.71");
//        name2Node.put("load11:", "11.1.32.72");
//        name2Node.put("load12:", "11.1.32.73");
//        int count = 0;
        try {
            FileReader reader = new FileReader("dispatcherStatus");
            BufferedReader bufedreader = new BufferedReader(reader);
            while (true) {
                ddStatus = bufedreader.readLine();
                if (ddStatus == null) {
                    break;
                }
                nodes.put(ddStatus.split("[|]")[0], name2Node.get(ddStatus.split("[|]")[0]));
            }
        } catch (Exception ex) {
            logger.error(ex, ex);
        }
        for (String name : name2Node.keySet()) {
            Map<String, String> map = new HashMap<String, String>();
            if (nodes.get(name) == null) {
                map.put("nodeName", name2Node.get(name));
                map.put("status", "error");
                map.put("message", "connection refused");
            } else {
                map.put("nodeName", name2Node.get(name));
                map.put("status", "ok");
                map.put("message", "");
            }
            list.add(map);
        }
        JSONArray jsonObj = JSONArray.fromObject(list);
        String info = "{result:'success', list:" + jsonObj.toString() + "}";
        //String info =  jsonObj.toString();
        JSONObject obj = JSONObject.fromObject(info);
        logger.info(obj);

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getWriter().println(obj);
    }
}

/*
 * 
 *         logger.info("receive request from " + remoteHost + ":" + remotePort + " and assigned id " + reqID);
        String tableName = baseRequest.getParameter("tablename");
        String direction = baseRequest.getParameter("direction");
        String node = baseRequest.getParameter("node");
        String dataCount = baseRequest.getParameter("datacount");
        List<Object> list = new ArrayList<Object>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("11.1.32.68", tableName);
        map.put("11.1.32.69", tableName);
        map.put("11.1.32.70", tableName);
        map.put("11.1.32.171", tableName);
        map.put("11.1.32.172", tableName);
        map.put("11.1.32.173", tableName);
        list.add(map);
        JSONArray jsonObj = JSONArray.fromObject(list);
        String info = "{result:'success', list:" + jsonObj.toString() + "}";
        JSONObject obj = JSONObject.fromObject(info);
        System.out.println(obj);
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getWriter().println(map);
 */